<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=400">
    <script src="../vendors/jquery/dist/jquery.min.js"></script>
    <title> PingChou </title>
<style type="text/css">
* {
    margin: 0;
    padding: 0;
}
body,html {
    height: 100%;
    overflow: hidden;
    background-color: #999999;
}

h1 {
    text-align: center;
}

#canvasId {
    background-color: #FFFFcc;
}

.button {
    width: 100px;
    height: 40px;
}
.box {
    width:100%;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    
}
.box img {
    width: 40px;
    height: 40px;
}
</style>
</head>
<body>
<!-- <h1>手写毛笔字效果-手机版</h1> -->
<h2><div>请抄写: <span id='r-txt'> </span></div></h2>
<canvas id="canvasId" width="400" height="400"></canvas><br />
<input type="button" value="全部清除" class="button" onclick="hw.clear();" />
<input type="button" value="清除最后一笔" class="button" onclick="hw.historyBack();" />
<button class="button" onclick="hw.createImg();">生成图片</button>
<h2><div style="color: #614A4A">
识别结果： <span id='txt'></span>
</div></h2>
<div class="box" id="box">
</div>
<script type="text/javascript">
    $(document).ready(function(){
        if (!getCookie('csrftoken')) {
            login_page = document.getElementById('login');
            if (login_page) {return}
            self.location='login.html'; 
        }
    })
</script>

<script type="text/javascript">

    // var txt = ["观","自","在","菩","萨","行","深","般","若","波","罗","蜜","多","时","照","见","五","蕴","皆","空","度","一","切","苦","厄","舍","利","子","色","不","异","即","是","受","想","识","亦","复","如","诸","法","相","生","灭","垢","净","增","减","故","中","无","，","眼","耳","鼻","舌","身","意","声","香","味","触","界","乃","至","。","明","尽","老","死","集","道","智","得","以","所","提","埵","依","心","罣","碍","有","恐","怖","远","离","颠","倒","梦","究","竟","涅","磐","三","世","佛","阿","耨","藐","知","大","神","咒","上","等","能","除","真","实","虚","说","曰","：","揭","谛","僧","婆","诃"]
    var txt = ['季', '荔', '嫩', '佳', '驹', '夷', '燃', '土', '柄', '滦', '刮', '强', '封', '酿', '温', '砖', '屁', '膀', '玲', '当', '仅', '近', '洗', '蝶', '族', '直', '窒', '揭', '赁', '黔', '卯', '郊', '垣', '跳', '努', '锻', '古', '档', '址', '蔬', '重', '横', '夫', '厘', '墓', '狙', '聋', '事', '笛', '淹', '段', '虞', '扣', '溉', '酋', '史', '冉', '七', '札', '抨', '炬', '粥', '赚', '怕', '赛', '汾', '吝', '潦', '抱', '绩', '砂', '捕', '幌', '双', '峭', '轨', '塑', '沤', '枣', '肝', '思', '承', '每', '瑞', '苍', '牙', '椽', '朴', '竖', '浚', '朔', '例', '惜', '冶', '娠', '耳', '些', '刹', '暖', '惊', '聪', '哩', '壬', '睦', '绰', '棚', '逛', '坏', '军', '胆', '孩', '兹', '挠', '毯', '谋', '雨', '午', '奥', '渡', '硅', '碳', '疮', '井', '祷', '诺', '葬', '敖', '落', '郝', '趋', '泣', '屉', '黑', '元', '修', '姿', '奄', '抑', '羞', '喳', '苫', '激', '搁', '司', '学', '啸', '柠', '紫', '谢', '歇', '全', '障', '哆', '最', '课', '敦', '扮', '奇', '绎', '港', '倪', '厚', '熙', '蜡', '晌', '唬', '柔', '裙', '可', '夕', '奔', '靡', '哼', '缚', '之', '袄', '创', '丁', '衣', '伤', '捻', '惯', '康', '瘤', '稍', '嘱', '辆', '捶', '啤', '路', '躲', '侣', '宝', '冤', '递', '箍', '琶', '墅', '穷', '氦', '俩', '腹', '帆', '健', '括', '尹', '女', '扁', '捌', '烫', '矾', '淌', '以', '扒', '凡', '敏', '瑰', '贯', '兔', '德', '吨', '某', '叛', '纶', '余', '暇', '凿', '墟', '墩', '肺', '缘', '涤', '解', '焉', '帅', '腰', '册', '叁', '翟', '良', '徘', '涛', '沙', '回', '岔', '川', '蜗', '贮', '赖', '邀', '枕', '囤', '咖', '舒', '包', '悔', '锗', '秤', '访', '绅', '淋', '琉', '约', '番', '辟']
    var txt_len = txt.length;
    var n_w;
    function ShowWord(){
        $('#r-txt').html('');
        n_w = txt[Math.floor(Math.random()*txt_len)];
        $('#r-txt').html(n_w); 
        return n_w;
    }

    n_w = ShowWord();
    var box = document.getElementById('box');
    box.style.height = document.body.clientHeight - 500;

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function Handwriting(id) {
        this.canvas = document.getElementById(id);
        this.ctx = this.canvas.getContext("2d");
        this.ctx.fillStyle = "rgba(0,0,0,0.5)";
        this.canvas.addEventListener("touchstart", this.downEvent.bind(this), false);
        this.canvas.addEventListener("touchmove", this.moveEvent.bind(this), false);
        this.canvas.addEventListener("touchend", this.upEvent.bind(this), false);
        this.canvas.addEventListener("contextmenu", function(e){ e.preventDefault() }, false);
        this.moveFlag = false;
        this.upof = {};
        this.radius = 0;
        this.has = [];
        this.startOf = null;
        this.lineMax = 30;
        this.lineMin = 3;
        this.linePressure = 1;
        this.smoothness = 80;
        this.history = [];
    }

    function WordImgUpload(Base64Img, n_w, hwStroke){
        var img = Base64Img.split(';base64,');
        var csrftoken = getCookie('csrftoken');
        data = {
        	'base64img': img[1],
            'r_txt': n_w,
            'hw_stroke': hwStroke,
        }
        $.ajax({
            url: '/fe/imgrecog/word',
            type: 'POST',
            data: data,
            async: false,
            dataType: 'json',
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data, status){
                if(data.status == 403){
                    self.location='login.html'; 
                    return
                }
                if(data.status == 200){
                    if(data.data.recg){
                        $('#txt').html(
                            "您书写正确(" + data.data.txt + ")")
                        n_w = ShowWord();
                    }else {
                        $('#txt').html(
                            "书写有误(" + data.data.txt + ")")
                    }
                }
                else{
                    alert('请求异常, 请刷新')
                }
            },
        });
    }

    Handwriting.prototype.createImg = function() {
        var canvas = this.canvas;
        if(this.isCanvasBlank(canvas)) {
            $('#txt').html("书写有误")
            return;
        }
        var url = canvas.toDataURL({format: 'png', quality: 1});
        WordImgUpload(url, n_w, this.history.length);
        this.clear();
    }


    Handwriting.prototype.isCanvasBlank=function(canvas) {
        var blank = document.createElement('canvas');
        blank.width = canvas.width;
        blank.height = canvas.height;
        return canvas.toDataURL() == blank.toDataURL();
    }

    Handwriting.prototype.clear = function () {
        this.history = [];
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
    }
    Handwriting.prototype.historyBack = function () {
        this.history.pop();
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
        for (var i = 0; i < this.history.length; i++) {
            var h = this.history[i];
            for (var j = 0; j < h.length; j+=3) {
                this.ctx.beginPath();
                this.ctx.arc(h[j],h[j+1],h[j+2],0,2*Math.PI,true);
                this.ctx.fill();
            }
        }
    }

    Handwriting.prototype.downEvent = function (e) {
        this.moveFlag = true;
        this.has = [];
        this.history.push([]);
        this.upof = this.getXY(e);
        this.startOf = this.upof;
    }

    Handwriting.prototype.moveEvent = function (e) {
        if (!this.moveFlag)
            return;
        e.preventDefault();
        var of = this.getXY(e);
        var up = this.upof;
        var ur = this.radius;
        this.has.unshift({time:new Date().getTime() ,dis:this.distance(up,of)});
        var dis = 0;
        var time = 0;
        for (var n = 0; n < this.has.length-1; n++) {
            dis += this.has[n].dis;
            time += this.has[n].time-this.has[n+1].time;
            if (dis>this.smoothness)
                break;
        }
        var or = Math.min(time/dis*this.linePressure+this.lineMin , this.lineMax) / 2;
        this.radius = or;
        this.upof = of;
        if (dis<7)
            return;
        if (this.startOf) {
            up = this.startOf;
            ur = or;
            this.startOf = null;
        }
        var len = Math.ceil(this.distance(up,of)/2);
        for (var i = 0; i < len; i++) {
            var x = up.x + (of.x-up.x)/len*i;
            var y = up.y + (of.y-up.y)/len*i;
            var r = ur + (or-ur)/len*i;
            this.ctx.beginPath();
            this.ctx.arc(x,y,r,0,2*Math.PI,true);
            this.ctx.fill();
            this.history[this.history.length-1].push(x,y,r);
        }
    }

    Handwriting.prototype.upEvent = function (e) {
        this.moveFlag = false;
    }

    Handwriting.prototype.getXY = function (e) {
        var x = e.touches[0].clientX;
        var y = e.touches[0].clientY;
        //var x = e.clientX;
        //var y = e.clientY;
        return {
            x : x - this.canvas.offsetLeft + (document.body.scrollLeft || document.documentElement.scrollLeft),
            y : y - this.canvas.offsetTop  + (document.body.scrollTop || document.documentElement.scrollTop)
        }
    }

    Handwriting.prototype.distance = function (a,b) {
        var x = b.x-a.x , y = b.y-a.y;
        return Math.sqrt(x*x+y*y);
    }

    var hw = new Handwriting("canvasId");
    hw.lineMax = 40;
    hw.lineMin = 3;
    hw.linePressure = 3.1;
    // hw.linePressure = 2.1;
    hw.smoothness = 100;
</script>
</body>
</html>

